// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'dart:async';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:sprintf/sprintf.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGButton.dart';

class QGMineOrderDetailPage extends StatefulWidget {
  dynamic data;
  QGMineOrderDetailPage({super.key, required this.data});
  @override
  State<QGMineOrderDetailPage> createState() => _QGMineOrderDetailPageState();
}

class _QGMineOrderDetailPageState extends State<QGMineOrderDetailPage> {
  Timer? timer;
  String? countdown;

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  onRefresh() {}

  getTime(timeNum) {
    var create = widget.data?["created"];

    if (create is String) {
      create = DateTime.parse(create).millisecondsSinceEpoch;
      create += timeNum * 60 * 1000;
      var dt = DateTime.fromMillisecondsSinceEpoch(create);

      create = sprintf("%d-%02d-%02d %02d:%02d:%02d",
          [dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second]);
    }

    return create; 
  }

  updateCountdown(timeNum) {
    countdown = getCountdown(getTime(timeNum));
    if (countdown != null) {
      timer?.cancel();
      timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        countdown = getCountdown(getTime(timeNum));
        if (countdown == null) {
          timer.cancel();
          widget.data["status"] = 3;
        }
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    var isSell = widget.data["status"] == 4;

    return QGScaffold(
        title: '订单详情',
        bgColor: Color(0XFF0c1012),
        body: Stack(
          children: [
            SingleChildScrollView(
              child: Container(
                child: Column(
                  children: [
                    buildHeader(),

                   Container(
                    transform: Matrix4.translationValues(0.0, -350.0, 0.0),
                    child: Column(
                      children: [
                    buildGoods(isSell),
                    //  isSell ? buildOrderInfo4Sell() : buildOrderInfo(),
                    isSell ? buildStateContainer() : Container(),
                    buildExtr(),
                    SizedBox(height: 74.rpx + max(20, kSafeBottom)),
                      ],
                    )
                  ),
                   
                 
                  ],
                ),
              ),
            ),
            Column(),
            buildBottom(),
          ],
        ));
  }

  buildbgImg() {
    return QGImage(asset: "sale_order_bg", width: kScreenWidth);
  }

  buildHeader() {
    var iamgeName;
    var state = "";
    var stateExt = "";
    var stateExt2 = "";

    switch (widget.data["status"]) {
      case 0:
        state = "支付成功 \n 支付成功，藏品正在转入中...";
        iamgeName = "sale_order_suc";
        break;
      case 1:
        state = "等待付款";
        stateExt = countdown ?? "";
        iamgeName = "sale_order_time";
        widget.data["tab"] == 1 ? updateCountdown(3) : updateCountdown(5);
        break;
      case 2:
        state = "发放中";
        iamgeName = "sale_order_time";
        break;
      case 3:
        state = "订单已取消";
        iamgeName = "sale_order_cancel";
        break;
      case 4:
        state = "藏品己售出，结算成功";
        iamgeName = "sale_order_suc";
        stateExt2 = "您寄售的藏品已被用户买入，寄售收入已到账至钱包余额";
        break;
      default:
        break;
    }

    return Stack(
      children: [
        buildbgImg(),
        Container(
          height: 104.rpx,
          padding: EdgeInsets.symmetric(horizontal: 10.rpx),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  iamgeName == null ? Container() : QGImage(asset: iamgeName,width: 30.rpx),
                  SizedBox(height: 10.rpx),
                  Text(
                    state,
                    style: TextStyle(
                        color: Color(0xFFFFFFFF),
                        fontSize: 16.rpx,
                        fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 5.rpx),
                  Text(
                    stateExt,
                    style: TextStyle(
                        color: Color(0xFFFFFFFF),
                        fontSize: 12.rpx,
                        fontWeight: FontWeight.normal),
                  ),
                ],
              ),
              widget.data["status"] == 4
                  ? Column(
                      children: [
                        SizedBox(height: 6.rpx),
                        Text(
                          stateExt2,
                          style: TextStyle(
                              color: Color(0xFF111111),
                              fontSize: 12.rpx,
                              fontWeight: FontWeight.normal),
                        ),
                      ],
                    )
                  : Container(),
            ],
          ),
        ),
      ],
    );
  }

  buildGoods(isSell) {
    var num = widget.data?["goods_num"] ?? widget.data?["good_num"];

    if (num is String) {
      num = "购买数量：$num";
    } else {
      num = "#${widget.data?["nft_no"]}/${widget.data?["total"]}";
    }

    return GestureDetector(
      // onTap: toMyNFT,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 10.rpx),
        padding: EdgeInsets.all(15.rpx),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.rpx),
          color: Color(0xFF232A32),
        ),
        child:Column(
          children: [
            Row(children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4.rpx),
            child: QGImage(
                url: widget.data["thumb_img"], width: 60.rpx, height: 60.rpx),
          ),
          SizedBox(width: 15.rpx),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.data["order_name"],
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 14.rpx,
                      fontWeight: FontWeight.normal),
                ),
                SizedBox(height: 12.rpx),
                Text(
                  num,
                  style: TextStyle(
                      color: Color(0xFF989EA4),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.normal),
                ),
                
              ],
            ),
          ),
        ]),

                SizedBox(height: 12.rpx),

   isSell ? buildOrderInfo4Sell() : buildOrderInfo(),

          ],
        )
        
         ,
      ),
    );
  }

  buildOrderInfo() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx, left: 10.rpx, right: 10.rpx),
    
      decoration: BoxDecoration(
        // borderRadius: BorderRadius.circular(6.rpx),
        // color: Color(0xFFFFFFFF),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(height: 0.5.rpx, color: Color(0xFF3D4854)),
          SizedBox(height: 15.rpx),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '订单金额：',
                style: TextStyle(
                    color: Color(0xFFffffff),
                    fontSize: 13.rpx,
                    fontWeight: FontWeight.normal),
              ),
              Text(
                '￥${widget.data?["total_fee"] ?? widget.data?["price"]}',
                style: TextStyle(
                    color: Color(0xFFffffff),
                    fontSize: 14.rpx,
                    fontWeight: FontWeight.bold),
              ),
            ],
          ),
          SizedBox(height: 10.rpx),
          GestureDetector(
            onTap: onCopy,
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 10.rpx),
              color: Colors.transparent,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '订单ID号：',
                    style: TextStyle(
                        color: Color(0xFFffffff),
                        fontSize: 13.rpx,
                        fontWeight: FontWeight.normal),
                  ),
                  Expanded(
                    child: Row(
                      // mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerRight,
                            child: Text(
                              widget.data["out_trade_no"] ?? "",
                              maxLines: 1,
                              style: TextStyle(
                                  color: Color(0xFFffffff),
                                  fontSize: 11.rpx,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                        SizedBox(width: 5.rpx),
                        QGImage(asset: "home_copy"),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildOrderInfo4Sell() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx, left: 10.rpx, right: 10.rpx),
      padding: EdgeInsets.only(
          left: 16.rpx, right: 16.rpx, top: 20.rpx, bottom: 15.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.rpx),
        color: Color(0xFFFFFFFF),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '订单详情',
            style: TextStyle(
                color: Color(0xFF111111),
                fontSize: 14.rpx,
                fontWeight: FontWeight.normal),
          ),
          SizedBox(height: 15.rpx),
          Container(height: 0.5.rpx, color: Color(0xFFEAEAEA)),
          SizedBox(height: 15.rpx),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '订单金额：',
                style: TextStyle(
                    color: Color(0xFF111111),
                    fontSize: 13.rpx,
                    fontWeight: FontWeight.normal),
              ),
              Text(
                '￥${widget.data["price"]}',
                style: TextStyle(
                    color: Color(0xFF111111),
                    fontSize: 14.rpx,
                    fontWeight: FontWeight.bold),
              ),
            ],
          ),
          SizedBox(height: 10.rpx),
          GestureDetector(
            onTap: onCopy,
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 10.rpx),
              color: Colors.transparent,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '订单ID号：',
                    style: TextStyle(
                        color: Color(0xFF111111),
                        fontSize: 13.rpx,
                        fontWeight: FontWeight.normal),
                  ),
                  Expanded(
                    child: Row(
                      // mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerRight,
                            child: Text(
                              widget.data["out_trade_no"] ?? "",
                              maxLines: 1,
                              style: TextStyle(
                                  color: Color(0xFF999999),
                                  fontSize: 11.rpx,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                        SizedBox(width: 5.rpx),
                        QGImage(asset: "home_copy"),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildStateContainer() {
    return Container(
        margin: EdgeInsets.only(top: 10.rpx, left: 10.rpx, right: 10.rpx),
        padding: EdgeInsets.symmetric(horizontal: 16.rpx, vertical: 20.rpx),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.rpx),
          color: Color(0xFFFFFFFF),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            '订单状态',
            style: TextStyle(
                color: Color(0xFF111111),
                fontSize: 14.rpx,
                fontWeight: FontWeight.normal),
          ),
          SizedBox(height: 15.rpx),
          Container(height: 0.5.rpx, color: Color(0xFFEAEAEA)),
          SizedBox(height: 15.rpx),
          buildState(items: [
            "藏品上架成功(${widget.data["created"] ?? ""})",
            "藏品已寄售，结算中",
            "藏品已寄售，结算成功(${widget.data["trade_time"] ?? ""})",
          ], current: 2),
        ]));
  }

  buildState({items, current}) {
    List<Widget> children = [];

    for (int i = 0; i < items.length; i++) {
      var dot = Container(
          width: 10.rpx,
          height: 10.rpx,
          decoration: i == current
              ? BoxDecoration(
                  color: const Color(0xFFDEFF80),
                  border: Border.all(
                      width: 1.5.rpx, color: const Color(0xFF111111)),
                  borderRadius: BorderRadius.circular(5.rpx),
                )
              : BoxDecoration(
                  borderRadius: BorderRadius.circular(5.rpx),
                  border: Border.all(width: 1.5.rpx, color: Color(0xFFCCCCCC)),
                  color: Color.fromRGBO(255, 255, 255, 1),
                ));

      var text = Expanded(
        child: Text(
          items[i],
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 13.rpx,
              fontWeight: FontWeight.normal),
        ),
      );
      children.add(Container(
          // color: Colors.amber,
          margin: EdgeInsets.only(top: 5.rpx, bottom: 5.rpx),
          child: Row(children: [dot, SizedBox(width: 15.rpx), text])));
    }

    return Stack(
      children: [
        Positioned(
            left: 4.rpx,
            top: 10.rpx,
            bottom: 10.rpx,
            child: Container(width: 2.rpx, color: const Color(0xFFCCCCCC))),
        Column(
          children: children,
        ),
      ],
    );
  }

  buildExtr() {
    return Container(
      alignment: Alignment.topLeft,
      margin: EdgeInsets.only(top: 20.rpx, left: 10.rpx, right: 10.rpx),
      child: Text(
        '说明：\n1.账号下有待支付订单时，不允许继续购买其他藏品\n2.同一账号一段时间内累计取消3次订单，超出次数将会被限购1小时',
        style: TextStyle(
            height: 2,
            color: Color(0xFF999999),
            fontSize: 11.rpx,
            fontWeight: FontWeight.normal),
      ),
    );
  }

  buildBottom() {
    var left = "";
    dynamic leftAction;
    var leftEnable = true;

    var right = "";
    dynamic rightAction;
    var rightEnable = true;
    switch (widget.data["status"]) {
      case 0:
      case 2:
      case 3:
      case 4:
        left = "我的藏品";
        leftAction = toMyNFT;
        right = "继续购买";
        rightAction = toTrade;
        break;
      case 1:
        left = "取消订单";
        leftAction = onCancel;
        right = "去支付";
        rightAction = onPay;
        break;
      default:
        break;
    }

    return Positioned(
        bottom: 0,
        child: Container(
          color: Color(0xFF232A32),
          padding: EdgeInsets.only(
              top: 10.rpx,
              left: 10.rpx,
              right: 10.rpx,
              bottom: max(10, kSafeBottom)),
          width: kScreenWidth,
          child: 
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(50.rpx),
              color: Color(0XFF111111)
            ),
            child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
               Expanded(
                  child: QGOutlineButton(
                      title: left, enable: leftEnable, onTap: leftAction)),
              Expanded(
                  child: QGButton(
                      title: right, enable: rightEnable, onTap: rightAction)),
            ],
          )
            ,
          )
          ,
        ));
  }

  onCopy() {
    Clipboard.setData(ClipboardData(
      text: widget.data["out_trade_no"] ?? "",
    ));
    toast("复制成功");
  }

  onCancel() {
    var url = url_market_cancelOrder;
    var num = widget.data?["goods_num"] ?? widget.data?["good_num"];
    if (num is String) {
      url = url_market_cancelBatchOrder;
    }

    var param = {};
    param['out_trade_no'] = widget.data["out_trade_no"];
Map<String, dynamic> stringMap = param.cast<String, dynamic>();
    Network.post(url, data: stringMap, context: context).then((res) async {
      toast(res.msg);
      if (!res.success) {
        return;
      }

      widget.data["status"] = 3;
      setState(() {});
    });
  }

  onPay() {
    var url = url_market_rePayOrder;
    var num = widget.data?["goods_num"] ?? widget.data?["good_num"];
    if (num is String) {
      url = url_market_rePayBatchOrder;
    }

    var param = {};
    param['out_trade_no'] = widget.data["out_trade_no"];
Map<String, dynamic> stringMap = param.cast<String, dynamic>();
    Network.post(url, data: stringMap, context: context).then((res) async {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      // res.data = decryptToJson(res.data);
      // if (res.data is! Map) {
      //   toast("数据解析失败");
      //   return;
      // }

      var url = res.data["pay_url"];
      Navigator.of(context).pushNamed(PageQGPayWebView, arguments: url);
    });
  }

  toTradeNFT() {
    Navigator.of(context).pushNamed(PageTradeNFTDetail,
        arguments: widget.data["collection_id"] ?? "");
  }

  toMyNFT() async {
    Navigator.of(context).pushNamed(PageMyNFT);
  }

  toTrade() async {
    Navigator.of(context).pop();
    Navigator.of(context).pop();
    eventBus.fire(EventMainTabSelectIndex(index: 1));
  }
}
